﻿using System;
using System.Collections;
using UnityEngine;
using UnityEngine.Networking;

namespace Defence
{
    public class AssetBundleLoad 
    {

        /// <summary>
        /// AssetBundle本地异步加载
        /// </summary>
        /// <typeparam name="T">加载类型</typeparam>
        /// <param name="path">加载包的路径</param>
        /// <param name="nam">加载物体名字</param>
        /// <returns></returns>
        public void LoadAsyncAssetMethod<T>(string path , string nam) where T : UnityEngine.Object
        {
            
        }

        public IEnumerator LoadAsyncAsset<T>(string path , string nam) where T : UnityEngine.Object
        {
            var ab = AssetBundle.LoadFromFileAsync(path);

            yield return ab;

            var prefab = ab.assetBundle.LoadAssetAsync<T>(nam);

            yield return prefab.asset;
        }

        /// <summary>
        /// 本地同步加载
        /// </summary>
        /// <typeparam name="T">加载类型</typeparam>
        /// <param name="path">加载包的路径</param>
        /// <param name="nam">加载包的名字</param>
        /// <returns></returns>
        public T LoadAsset<T>(string path , string nam) where T : UnityEngine.Object
        {
            var ab = AssetBundle.LoadFromFile(path);

            var prefab = ab.LoadAsset<T>(nam);

            return prefab;
        }

        /// <summary>
        /// UnityWebRequestAssetBundle 网络加载方式
        /// </summary>
        /// <typeparam name="T">加载类型</typeparam>
        /// <param name="path">加载的包的路径</param>
        /// <param name="nam">加载物体的名字</param>
        /// <returns></returns>
        public IEnumerator LoadAssetBundle<T>(string path , string nam)
        {
            using (UnityWebRequest request = UnityWebRequestAssetBundle.GetAssetBundle(path))
            {
                yield return request.SendWebRequest();

                if (request.isHttpError || request.isHttpError)
                {
                    throw new Exception($"下载错误{request.error}");
                }

                var ab = ( request.downloadHandler as DownloadHandlerAssetBundle ).assetBundle;

                var prefab = ab.LoadAssetAsync<T>(nam);

                yield return prefab;
            }
        }
    }
}